//
//  MYGpatientImageListVC.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/30.
//

import UIKit

class MYGpatientImageListVC: MYGBaseController {
    var dataSource = [MYGPatientImages]()
    var patientId = 0
    var sortKey = 0//DESC降序/ ASC 升序
    var patientName:String = ""
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "检查影像"
        let rightBar = UIBarButtonItem(image: UIImage.init(named: "Myg_addImages"), style: .plain, target: self, action: #selector(tapAddImage))
        self.navigationItem.rightBarButtonItem = rightBar
        setUpUI()
        getData()
        NotificationCenter.default.addObserver(self, selector: #selector(popUpDismiss), name: NSNotification.Name("JFPopupController_dismiss"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(getData), name: NSNotification.Name("MYGpatientImageListVC_configDataSource"), object: nil)
    }
    
    lazy var nameLB: UILabel = {
        let control = UILabel()
        control.textColor = UIColor.init(hexString: "#232323")
        control.font = .regular(15)
        control.textAlignment = .left
        control.text = "\(patientName)的检查影像"
        return control
    }()
    lazy var sortBtn: UIButton = {
        let control = UIButton()
        control.setTitleColor(UIColor.init(hexString: "#808080"), for: [])
        control.titleLabel?.font = .regular(12)
        control.setTitle("时间倒序", for: .normal)
        control.imageEdgeInsets = UIEdgeInsets(top: 0, left: 60, bottom: 0, right: 0)
        control.titleEdgeInsets = UIEdgeInsets(top: 0, left: -20, bottom: 0, right: 0)
        control.setImage(UIImage.init(named: "MYG_cloudDisk_arrow_down"), for: .normal)
        control.addTarget(self, action: #selector(tapSort), for: .touchUpInside)
        return control
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .vertical
        layout.minimumLineSpacing = 12
        layout.minimumInteritemSpacing = 4
        var leftMargin = 12.0
        var midMargin = 8.0
        let itemWidth = (screenWidth - 2 * leftMargin - 2 * midMargin) / 3
        layout.itemSize = CGSize(width: itemWidth, height: 137)
        let control = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        control.register(UINib.init(nibName: "MYGImagesSelectedCell", bundle: nil), forCellWithReuseIdentifier: "MYGImagesSelectedCell")
        control.showsHorizontalScrollIndicator = false
        control.showsVerticalScrollIndicator = false
        control.backgroundColor = .white
        control.delegate = self
        control.dataSource = self
        control.contentInset = UIEdgeInsets(top: 0, left: leftMargin, bottom: 0, right: leftMargin)
        return control
    }()
    
    
    func setUpUI() {
        view.addSubview(nameLB)
        nameLB.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(15)
        }
        view.addSubview(sortBtn)
        sortBtn.snp.makeConstraints { make in
            make.right.equalToSuperview().offset(-15)
            make.size.equalTo(CGSize.init(width: 75, height: 30))
            make.centerY.equalTo(nameLB.snp.centerY)
        }
        view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.top.equalTo(sortBtn.snp.bottom)
            make.left.right.bottom.equalToSuperview()
        }
        
    }
    @objc func tapAddImage() {
        self.popup.dialog(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = Bundle.main.loadNibNamed("MYGAddPatientImageAlert", owner: nil)?.first as! MYGAddPatientImageAlert
            actionSheet.tapCopyCompletion = {text in
                let pasteboard = UIPasteboard.general
                pasteboard.string = text
                JFPopupView.popup.toast(hit: "已复制到剪切板")
                self.popup.dismissPopup()
            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: 315, height: 191)
            actionSheet.layer.cornerRadius = 12
            actionSheet.layer.masksToBounds = true
            return actionSheet
        }
    }
    
    //监听弹窗dismiss
    @objc func popUpDismiss() {
        self.dataSource = self.dataSource.map({ model in
            var obj = model
            obj.selected = false
            return obj
        })
        self.collectionView.reloadData()
    }
    
    
   @objc func getData() {
        self.dataSource.removeAll()
        let sort = self.sortKey == 0 ? "desc" : "asc"
        MYGLoading.show()
        DennyNetwork.request(MYGPatientImageApi.examinationList(patient_id: self.patientId, sort: sort), modelType: [MYGPatientImages].self) { obj in
            MYGLoading.hide()
            self.dataSource = obj
            self.collectionView.reloadData()
        } failed: { code, message in
            MYGLoading.hide()
            MMYGHUD.showToast(text: message)
        }


    }
    @objc func tapSort() {
        YBPopupMenu.show(at: CGPoint(x: screenWidth - 25, y: navHeight + statusBarHeight + 38), titles: ["时间倒叙","时间升序"], icons: [], menuWidth: 85) { menu in
            menu?.delegate = self
            menu?.dismissOnSelected = true
            menu?.font = UIFont.regular(12)
            menu?.itemHeight = 30
            menu?.selectecIndex = self.sortKey
            menu?.selectedTextColor = UIColor.init(hexString: "#6389F1")
            menu?.separatorColor = .clear
            menu?.textColor = UIColor.init(hexString: "#C0BEBE")
        }
    }
}

extension MYGpatientImageListVC:YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
        self.sortKey = index
        let title = self.sortKey == 0 ? "时间倒序": "时间升序"
        sortBtn.setTitle(title, for: .normal)
        getData()
    }
}

extension MYGpatientImageListVC:UICollectionViewDataSource,UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "MYGImagesSelectedCell", for: indexPath) as! MYGImagesSelectedCell
        let model = self.dataSource[indexPath.row]
        cell.model = model
        cell.tapBoxCompletion = {[weak self]obj in
            self?.didSelectedBox(model: obj)
        }
        return cell
    }
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.dataSource.count
    }
    
    func didSelectedBox(model:MYGPatientImages) {
        self.dataSource = self.dataSource.map({ obj in
            var result = obj
            result.selected = (obj.id == model.id)
            return result
        })
        self.collectionView.reloadData()
        self.popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = Bundle.main.loadNibNamed("MYGPatientImageEditAlert", owner: nil)?.first as! MYGPatientImageEditAlert
            actionSheet.model = model
            
            //重命名
            actionSheet.tapRenameCompletion = {[weak self] obj in
                self?.popup.dismissPopup()
                self?.showRenameAlert(id: obj.id)
            }
            //分享
            actionSheet.tapShareCompletion =  {[weak self] obj in
                self?.popup.dismissPopup()
                self?.toShare(obj: obj)
            }
            //删除
            actionSheet.tapDeleteCompletion = {[weak self] obj in
                self?.popup.dismissPopup()
                self?.goDelete(id: obj.id)
            }
            
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 50 + bottomSafeheight)
            return actionSheet
        }
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let model = self.dataSource[indexPath.row]
        let vc = MYGpatientImageDetailVC()
        vc.pid = model.id
        self.navigationController?.pushViewController(vc)
    }
    
    func showRenameAlert(id:Int) {
        self.popup.dialog(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let alert = Bundle.main.loadNibNamed("MYGCloudDiskRenameFileAlert", owner: nil)?.first as! MYGCloudDiskRenameFileAlert
            alert.frame = CGRect.init(x: 0, y: 0, width: screenWidth - 30, height: 210)
            let  model = MYCloudDiskContentModel()
            model.id = "\(id)"
            alert.isRename = true
            alert.isPatientImage = true
            alert.fileModel = model
        
            alert.tapClosePageCompletion = {
                self.popup.dismissPopup()
            }
            return alert
        }
    }
    
    func goDelete(id:Int) {
        MYGLoading.show()
         MYGNetwork<MYGPatientImageApi, MYGEmptyModel>.request(target: .deleteImageExamination(id: id)) {[weak self] item in
             self?.getData()
             MYGLoading.hide()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func toShare(obj:MYGPatientImages) {
        self.popup.bottomSheet(with: true, bgColor: .black.withAlphaComponent(0.43)) {
            let actionSheet = Bundle.main.loadNibNamed("MYGPatientImageShareAlert", owner: nil)?.first as! MYGPatientImageShareAlert
            actionSheet.model = obj
            
            actionSheet.tapIMCompletion = {[weak self]data in
                self?.popup.dismissPopup()
                let vc = MYGSelectDoctorVC()
                vc.patientModel = data
                self?.navigationController?.pushViewController(vc)
            }
            actionSheet.tapPhoneCompletion = {[weak self]data in
                self?.popup.dismissPopup()
                let vc = MYGSelectDoctorVC()
                vc.patientModel = data
                self?.navigationController?.pushViewController(vc)
                
            }
            actionSheet.frame = CGRect.init(x: 0, y: 0, width: screenWidth, height: 247 + bottomSafeheight)
            return actionSheet
        }
    }
}
 
